package com.example.synatx.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;

/**
 * @author guoxh
 * @date 2020/2/15-18:25
 * @desc
 * LocalDate 该类的实例是一个不可变对象,它只提供简单的日期,并不含当天的时间信息.另外也不附带任何和时区有关的信息.
 */
public class LocalDateTest {

    public void test01(){
        LocalDate date = LocalDate.of(2019,12,31);
        date = LocalDate.now();
        int year = date.getYear();
        int monthValue = date.getMonthValue();
        Month month = date.getMonth();
        int day = date.getDayOfMonth();
        boolean flag = date.isLeapYear();
    }

    public void test02(){
        LocalDate date = LocalDate.now();
        int year = date.get(ChronoField.YEAR);
        int month = date.get(ChronoField.MONTH_OF_YEAR);
        int day = date.get(ChronoField.DAY_OF_YEAR);
    }

    public void test03(){
        LocalDate localDate = LocalDate.parse("2020-02-16");
        System.out.println(localDate.toString());
    }

    /**
     * 对已有的localDate对象创建一个它的修改版,可以使用withAttribute方法,withAttribute方法会创建该对象的一个副本,并按照需要修改它的属性.
     * 返回的对象都是已经修改了属性的对象,不会修改原始对象.
     */
    public void test04(){
        LocalDate localDate = LocalDate.now();

        LocalDate localDate1 = localDate.withYear(2019);
        LocalDate localDate2 = localDate.with(ChronoField.DAY_OF_MONTH,15);
    }

    public void test05(){
        LocalDate localDate = LocalDate.now();
        LocalDate localDate1 = localDate.plusWeeks(1);
        LocalDate localDate2 = localDate.minusYears(2);
        LocalDate localDate3 = localDate.plus(2, ChronoUnit.YEARS);
    }

    /**
     * 预定义的TemporalAdjuster.
     * TemporalAdjuster 对象可以进行更复杂的日期操作,比如将日期调整为下个周日,下个工作日,或者是本月的最后一天等.
     */
    public void test06(){
        LocalDate localDate = LocalDate.now();
        LocalDate localDate1 = localDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        LocalDate localDate2 = localDate.with(TemporalAdjusters.lastDayOfMonth());
    }

    /**
     * 如果要使用lambda表达式定义TemporalAdjuster对象,推荐使用TemporalAdjusters类的静态工厂方法ofDateAdjuster.
     * 它接受一个UnaryOperator<LocalDate>类型的参数
     */
    public void test07(){
        TemporalAdjuster nextWorkingDay = TemporalAdjusters.ofDateAdjuster(
                temporal ->{
                    DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK));
                    int dayAdd = 1;
                    if (dayOfWeek == DayOfWeek.FRIDAY){
                        dayAdd = 3;
                    }else if(dayOfWeek == DayOfWeek.SATURDAY){
                        dayAdd = 2;
                    }
                    return temporal.plus(dayAdd,ChronoUnit.DAYS);
                });
    }

}
